package com.dhcc.utils;

import java.util.HashMap;
import java.util.Map;

/**
 * 文件处理工具类
 * @ProjectName Dhcc-Cloud
 * @PackageName com.dhcc.utils
 * @Title FileUtil
 * @Date 2025/6/6 00:09
 * @Author LiuGuoting
 */
public class FileUtil {
    /**
     * 文件类型映射
     */
    private static final Map<String, String> FILE_TYPES = new HashMap<>();

    static {
        // 静态初始化块，初始化文件类型映射
        FILE_TYPES.put("txt", "text/plain");
        FILE_TYPES.put("html", "text/html");
        FILE_TYPES.put("css", "text/css");
        FILE_TYPES.put("js", "text/javascript");
        FILE_TYPES.put("json", "application/json");
        FILE_TYPES.put("jpg", "image/jpeg");
        FILE_TYPES.put("jpeg", "image/jpeg");
        FILE_TYPES.put("png", "image/png");
        FILE_TYPES.put("gif", "image/gif");
        FILE_TYPES.put("svg", "image/svg+xml");
        FILE_TYPES.put("mp3", "audio/mpeg");
        FILE_TYPES.put("wav", "audio/wav");
        FILE_TYPES.put("ogg", "audio/ogg");
        FILE_TYPES.put("mp4", "video/mp4");
        FILE_TYPES.put("mpeg", "video/mpeg");
        FILE_TYPES.put("pdf", "application/pdf");
        FILE_TYPES.put("doc", "application/msword");
        FILE_TYPES.put("docx", "application/docx");
        FILE_TYPES.put("xls", "application/vnd.ms-excel");
        FILE_TYPES.put("xlsx", "application/xlsx");
        FILE_TYPES.put("zip", "application/zip");
        FILE_TYPES.put("gz", "application/x-gzip");
        FILE_TYPES.put("tar", "application/x-tar");
    }

    /**
     * 根据文件扩展名获取文件类型
     *
     * @param fileName 文件名
     * @return 文件类型，如果找不到则返回null
     */
    public static String getFileType(String fileName) {
        // 获取文件后缀
        int dotIndex = fileName.lastIndexOf(".");
        if (dotIndex == -1) {
            // 没有后缀，无法确定文件类型，返回null
            return null;
        }
        String extension = fileName.substring(dotIndex + 1).toLowerCase();
        // 查找文件类型映射
        return FILE_TYPES.get(extension);
    }
}
